package com.belf.console.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.belf.common.config.MigrateConfig;
import com.belf.common.constant.HttpStatus;
import com.belf.common.core.domain.AjaxResult;
import com.belf.common.core.domain.entity.SysDictData;
import com.belf.common.core.domain.entity.SysUser;
import com.belf.common.utils.DateUtils;
import com.belf.console.agent.migrate.job.BuildDataSourceConf;
import com.belf.console.domain.DataSourceInfo;
import com.belf.console.mapper.DataSourceInfoMapper;
import com.belf.console.service.IDataSourceInfoService;
import com.belf.system.service.ISysDictDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

import static com.belf.common.constant.BelfCodeConstants.*;
import static com.belf.common.core.domain.AjaxResult.DATA_TAG;

/**
 * 数据源信息Service业务层处理
 * 
 * @author belf
 * @date 2024-06-20
 */
@Service
public class DataSourceInfoServiceImpl implements IDataSourceInfoService {

    @Autowired
    private DataSourceInfoMapper dataSourceInfoMapper;
    @Autowired
    private MigrateConfig migrateConfig;
    @Autowired
    private ISysDictDataService dictDataService;

    private static  Logger LOGGER = LoggerFactory.getLogger(DataSourceInfoServiceImpl.class.getName());

    /**
     * 查询数据源信息
     *
     * @param id 数据源信息主键
     * @return 数据源信息
     */
    @Override
    public DataSourceInfo selectDataSourceInfoById(String id)
    {
        return dataSourceInfoMapper.selectDataSourceInfoById(id);
    }

    /**
     * 查询数据源信息列表
     * 
     * @param dataSourceInfo 数据源信息
     * @return 数据源信息
     */
    @Override
    public List<DataSourceInfo> selectDataSourceInfoList(DataSourceInfo dataSourceInfo)
    {
        return dataSourceInfoMapper.selectDataSourceInfoList(dataSourceInfo);
    }

    @Override
    public long selectDataCount(DataSourceInfo dataSourceInfo)
    {
        return dataSourceInfoMapper.selectDataCount(dataSourceInfo);
    }

    @Override
    public List<DataSourceInfo> selectDataSourceInfoByIds(String[] ids) {
        return dataSourceInfoMapper.selectDataSourceInfoByIds(ids);
    }

    /**
     *  数据统计
     * @param user
     * @return
     */
    @Override
    public AjaxResult selectDataSourceInfoCount(SysUser user) {
        DataSourceInfo dataSourceInfo = new DataSourceInfo();
        dataSourceInfo.setDataType(1);
        if (!user.isAdmin()){
            dataSourceInfo.setCreateBy(user.getUserName());
        }
        HashMap<String,Integer> dataTestCount=dataSourceInfoMapper.selectDataTestCount(dataSourceInfo);
        HashMap<String,Integer> dataTypeCount=dataSourceInfoMapper.selectDataTypeCount(dataSourceInfo);

        AjaxResult success = AjaxResult.success();
        success.put("dataCount",dataTestCount);
        success.put("dataTypeCount",dataTypeCount);
        return success;
    }



    /**
     * 新增数据源信息
     * 
     * @param dataSourceInfo 数据源信息
     * @return 结果
     */
    @Override
    public int insertDataSourceInfo(DataSourceInfo dataSourceInfo)
    {
        dataSourceInfo.setCreateTime(DateUtils.getNowDate());
        dataSourceInfo.setUpdateTime(DateUtils.getNowDate());
        return dataSourceInfoMapper.insertDataSourceInfo(dataSourceInfo);
    }

    /**
     * 修改数据源信息
     * 
     * @param dataSourceInfo 数据源信息
     * @return 结果
     */
    @Override
    public int updateDataSourceInfo(DataSourceInfo dataSourceInfo)
    {
        dataSourceInfo.setUpdateTime(DateUtils.getNowDate());
        return dataSourceInfoMapper.updateDataSourceInfo(dataSourceInfo);
    }

    /**
     * 批量删除数据源信息
     * 
     * @param ids 需要删除的数据源信息主键
     * @return 结果
     */
    @Override
    public int deleteDataSourceInfoByIds(String[] ids)
    {
        return dataSourceInfoMapper.deleteDataSourceInfoByIds(ids);
    }

    /**
     * 删除数据源信息信息
     * 
     * @param id 数据源信息主键
     * @return 结果
     */
    @Override
    public int deleteDataSourceInfoById(String id)
    {
        return dataSourceInfoMapper.deleteDataSourceInfoById(id);
    }

    /**
     * 数据源信息 连接测试
     *
     * @return 结果
     */
    @Override
    public AjaxResult databaseCheck(DataSourceInfo dataSourceInfo) {
        if (dataSourceInfo.getId()!=null){
            dataSourceInfo = dataSourceInfoMapper.selectDataSourceInfoById(dataSourceInfo.getId());
        }
//        setDataSourceDatabase(dataSourceInfo, dataSourceInfo.getDatabaseName());
        AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.getTestConnect(), dataSourceInfo);
        JSONObject resultData = JSONObject.from(ajaxResult.get(DATA_TAG));

        if (ajaxResult.isSuccess()){
            dataSourceInfo.setTestStatus(BELF_DATASOURCE_LINE_OFF);
            if (HttpStatus.SUCCESS==(resultData.getInteger(AjaxResult.CODE_TAG))){
                dataSourceInfo.setTestStatus(BELF_DATASOURCE_LINE_ON);
            }
            dataSourceInfoMapper.updateDataSourceInfo(dataSourceInfo);
        }
        return ajaxResult;
    }

    /**
     * 数据源信息 获取数据库
     *
     * @return 结果
     */
    @Override
    public AjaxResult dataSourceGetDBS(DataSourceInfo dataSourceInfo) {
        if (dataSourceInfo.getId()!=null){
            dataSourceInfo = dataSourceInfoMapper.selectDataSourceInfoById(dataSourceInfo.getId());
//            setDataSourceDatabase(dataSourceInfo, dataSourceInfo.getDatabaseName());
            AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.getQueryDatabase(), dataSourceInfo);
            return ajaxResult;
        }
        return AjaxResult.error();
    }

    /**
     * 数据源信息 获取表
     *
     * @return 结果
     */
    @Override
    public AjaxResult dataSourceGetTables(DataSourceInfo dataSourceInfo) {
        String databaseName = dataSourceInfo.getDatabaseName();
        String schemaName = dataSourceInfo.getSchemaName();
        dataSourceInfo = dataSourceInfoMapper.selectDataSourceInfoById(dataSourceInfo.getId());
        if (dataSourceInfo!=null && dataSourceInfo.getId()!=null){
            if (schemaName!=null){
                dataSourceInfo.setSchemaName(schemaName);
            }
            if (databaseName!=null){
                dataSourceInfo.setDatabaseName(databaseName);
            }
            AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.getQueryTables(), dataSourceInfo);
            return ajaxResult;
        }
        return AjaxResult.error();
    }


    /**
     * 数据源信息 获取表
     *
     * @return 结果
     */
    @Override
    public AjaxResult dataSourceGetObjects(DataSourceInfo dataSourceInfo) {
        String databaseName = dataSourceInfo.getDatabaseName();
        String schemaName = dataSourceInfo.getSchemaName();
        String taskMode = dataSourceInfo.getTaskMode();
        dataSourceInfo = dataSourceInfoMapper.selectDataSourceInfoById(dataSourceInfo.getId());
        if (dataSourceInfo!=null && dataSourceInfo.getId()!=null){
            dataSourceInfo = dataSourceInfoMapper.selectDataSourceInfoById(dataSourceInfo.getId());
            if (schemaName!=null){
                dataSourceInfo.setSchemaName(schemaName);
            }
            if (databaseName!=null){
                dataSourceInfo.setDatabaseName(databaseName);
            }
            dataSourceInfo.setTaskMode(taskMode);
            AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.getQueryObjects(), dataSourceInfo);
            return ajaxResult;
        }
        return AjaxResult.error();
    }

    public void setDataSourceDatabase(DataSourceInfo dataSourceInfo,String databaseName){
        if (databaseName!=null){
            SysDictData sysDictDataBean = new SysDictData();
            sysDictDataBean.setDictType(DATASOURCE_DATABASE_DICT);
            sysDictDataBean.setDictLabel(dataSourceInfo.getType());

            List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(sysDictDataBean);
            if (sysDictDataList != null && sysDictDataList.size() > 0) {
                SysDictData sysDictData = sysDictDataList.get(0);
                if (sysDictData.getDictValue().equals(BELF_DATASOURCE_DATABASE)){
                    dataSourceInfo.setDatabaseName(databaseName);
                }
                if (sysDictData.getDictValue().equals(BELF_DATASOURCE_SCHEMA)){
                    dataSourceInfo.setSchemaName(databaseName);
                }
            }
        }
    }

    @Override
    public AjaxResult dataSourceGetColumns(DataSourceInfo dataSourceInfo) {
        String databaseName = dataSourceInfo.getDatabaseName();
        String schemaName = dataSourceInfo.getSchemaName();
        String tableName = dataSourceInfo.getTableName();
        dataSourceInfo = selectDataSourceInfoById(dataSourceInfo.getId());
        if (dataSourceInfo!=null && dataSourceInfo.getId()!=null){
            if (schemaName!=null){
                dataSourceInfo.setSchemaName(schemaName);
            }
            if (databaseName!=null){
                dataSourceInfo.setDatabaseName(databaseName);
            }
            dataSourceInfo.setTableName(tableName);
            AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.getQueryColumns(), dataSourceInfo);
            return ajaxResult;
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult dataSourceGetDbColumns(DataSourceInfo dataSourceInfo) {
        String databaseName = dataSourceInfo.getDatabaseName();
        String schemaName = dataSourceInfo.getSchemaName();
        String[] tableNames = dataSourceInfo.getTableNames();
        dataSourceInfo = selectDataSourceInfoById(dataSourceInfo.getId());
        if (dataSourceInfo!=null && dataSourceInfo.getId()!=null){
            if (schemaName!=null){
                dataSourceInfo.setSchemaName(schemaName);
            }
            if (databaseName!=null){
                dataSourceInfo.setDatabaseName(databaseName);
            }
            dataSourceInfo.setTableNames(tableNames);
            AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.getDbColumns(), dataSourceInfo);
            return ajaxResult;
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult listDatabaseAndSchema(DataSourceInfo dataSourceInfo) {
//        String databaseName = dataSourceInfo.getDatabaseName();
//        String schemaName = dataSourceInfo.getSchemaName();
        dataSourceInfo = selectDataSourceInfoById(dataSourceInfo.getId());
        if (dataSourceInfo!=null && dataSourceInfo.getId()!=null){
//            setDataSourceDatabase(dataSourceInfo, databaseName);
//            dataSourceInfo.setSchemaName(schemaName);
//            dataSourceInfo.setDatabaseName(databaseName);
            AjaxResult ajaxResult = BuildDataSourceConf.queryDataSource(migrateConfig.listDatabaseAndSchema(), dataSourceInfo);
            return ajaxResult;
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult listConfigDbTypes(DataSourceInfo dataSourceInfo) {
//        "catalog": "DAMENG"
       return BuildDataSourceConf.queryDataDbTypes(migrateConfig.configDbTypes(), dataSourceInfo);
    }
}
